package qf.sail.controller;

import qf.sail.contents.CodeMsg;
import qf.sail.service.OrderService;
import qf.sail.service.impl.OrderServiceImpl;
import qf.sail.util.Alipay;
import qf.sail.vo.ResultVO;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;

@WebServlet("/toAliPay")
public class ToAliPayServlet extends BaseServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        OrderService orderService = new OrderServiceImpl();

        //获取支付金额
        BigDecimal payMoney = null;
        try {
            payMoney = new BigDecimal(req.getParameter("payMoney"));
        } catch (Exception e){
            repError(resp, CodeMsg.PAY_MONEY_ERR);
            return;
        }
        if(payMoney.compareTo(new BigDecimal(0)) <= 0){
            repError(resp, CodeMsg.PAY_MONEY_ERR);
            return;
        }

        //判断支付方式
        String payType = req.getParameter("payType");
        if (!payType.equals("ali_pay")){
            repError(resp, CodeMsg.PAY_TYPE_ERR);
        }

        //更改订单地址
        orderService.updateOrderAddress(req.getParameter("address"),Long.parseLong(req.getParameter("orderId")));


        //跳转支付页面
        String sn = req.getParameter("sn");
        String html = Alipay.generatePayHtml(sn, payMoney, "用户支付", "用户支付了【" + payMoney + "】");
        System.out.println("发起订单号为："+sn+"的支付，支付金额为："+payMoney);
        ResultVO resultVO = new ResultVO();
        resultVO.addData("payHtml",html);
        repSuccess(resp,resultVO);
    }
}
